package com.gh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.listener.DictListener;
import com.gh.mapper.DictMapper;
import com.gh.model.cmn.Dict;
import com.gh.service.DictService;
import com.gh.vo.cmn.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Eric
 * @Date 2021/6/5 23:53
 * @Version 1.0
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findListById(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> list = baseMapper.selectList(queryWrapper);
        list.forEach(item -> {
            item.setHasChildren(isExistChildren(item.getId()));
        });
        return list;
    }

    /**
     * 导出数据字典
     * @param response
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void exportDictToExcel(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");//application/vnd.ms-excel
        response.setCharacterEncoding("utf-8");
        String filename="dict";
        response.setHeader("Content-disposition", "attachment;filename="+ filename + ".xlsx");
        //查询数据
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> list=new ArrayList<>();
        for (Dict dict : dictList) {
            DictEeVo dictEeVo=new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            list.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet().doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importDictToDatabase(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            return dict.getName();
        }else {
            Dict dict = this.getDictByDictCode(dictCode);
            Long id = dict.getId();
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("parent_id",id);
            queryWrapper.eq("value",value);
            Dict dic = baseMapper.selectOne(queryWrapper);
            return dic.getName();
        }
    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(queryWrapper);
        return codeDict;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取id
        Dict dict = this.getDictByDictCode(dictCode);
        List<Dict> list = this.findListById(dict.getId());
        return list;
    }

    /**
     * 判断id下面有没有子节点
     */
    private Boolean isExistChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
